#!/usr/bin/python
# -*- coding: utf-8 -*-

from PyQt4 import QtGui, QtCore
import sys
import operator

class List(QtGui.QTableView):
    
    @classmethod
    def to_data(cls, list, headers):
        data = []
        for i in range(len(headers)):
            data.append([headers[i], list[i]])
        return data
    
    def __init__(self, headers):
        QtGui.QTableView.__init__(self)
        self.longest_header = "1"
        self.items = MovieTableModel(self)
        self.setModel(self.items)
        
        self.set_headers(headers)
        
        self.setShowGrid(True)
        
        vh = self.verticalHeader()
        vh.setVisible(False)
        vh.setDefaultSectionSize(23)
        hh = self.horizontalHeader()
        hh.setStretchLastSection(True)
        hh.setVisible(False)

        # set column width to fit contents
        self.setSelectionMode(QtGui.QTableView.NoSelection) 
        self.setSelectionBehavior(QtGui.QTableView.SelectRows)
        self.resizeColumnsToContents()
       
    def set_movie(self, list):
        data = self.to_data(list, self.headers)
        self.items.arraydata = data
        self.updateList()
    
    def clear(self):
        self.items.arraydata = []
        self.updateList()
    
    def updateList(self):
        self.resizeColumnsToContents()
        hh = self.horizontalHeader()
        hh.setStretchLastSection(True)
        self.items.emit(QtCore.SIGNAL("layoutChanged()"))
                    
    def set_headers(self, headers):
        self.headers = headers
        max = 0
        maxc = self.headers[0]
        for c in self.headers:
            if len(c) > max:
                max = len(c)
                maxc = c
        self.longest_header = maxc
        self.updateList()
             
class MovieTableModel(QtCore.QAbstractTableModel): 
    def __init__(self, parent, *args): 
        QtCore.QAbstractTableModel.__init__(self, parent, *args)
        self.arraydata = []
        self.tableParent = parent
 
    def rowCount(self, parent=None):
        if len(self.arraydata) == 0:
            return 0 
        return len(self.arraydata) 
 
    def columnCount(self, parent=None): 
        return 2
    
    def data(self, index, role):
        if not index.isValid(): 
            return QtCore.QVariant() 
        elif role != QtCore.Qt.DisplayRole:
            if role == QtCore.Qt.BackgroundColorRole and index.column() == 0:
                return QtCore.QVariant(self.tableParent.palette().alternateBase())  
            return QtCore.QVariant()
        d = self.arraydata[index.row()][index.column()]
        return QtCore.QVariant(d)
    
    def headerData(self, col, orientation, role):
        if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.TextAlignmentRole:
            return QtCore.QVariant(int(QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter))
        if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
            return QtCore.QVariant(self.tableParent.longest_header)
        return QtCore.QVariant()

def flow(widgets, horiz=True):
    panel = QtGui.QWidget()
    layout = QtGui.QHBoxLayout() if horiz else QtGui.QVBoxLayout()
    layout.setMargin(0)     
    for w in widgets:
        if type(w) == int:
            layout.addSpacing(w)
        elif type(w) == tuple:
            layout.addWidget(w[0], w[1])
        elif w == "stretch":
            layout.addStretch(0)
        else:
            layout.addWidget(w)
    panel.setLayout(layout)
    return panel

class InputDialog(QtGui.QDialog):
    def __init__(self, parent):
        QtGui.QDialog.__init__(self, parent)
        self.setModal(True)
        self.ok = False
        
        self.groupLabel = QtGui.QLabel("Group:")
        self.groupLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter)
        
        self.groupBox = QtGui.QComboBox(self)
        for p in plugins.groups.keys():
            self.groupBox.addItem(p)
                
        self.queryLabel = QtGui.QLabel("Search:")
        self.queryLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter)
        self.queryEdit = QtGui.QLineEdit(self)
        
        self.btnBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok
                                            | QtGui.QDialogButtonBox.Cancel)
        self.connect(self.btnBox, QtCore.SIGNAL('accepted()'), self._ok);
        self.connect(self.btnBox, QtCore.SIGNAL('rejected()'), self.close);
        
        form = QtGui.QWidget()
        self.formLayout = QtGui.QGridLayout()
        self.formLayout.setMargin(0)
        self.formLayout.addWidget(self.groupLabel, 0, 0)
        self.formLayout.addWidget(self.groupBox, 0, 1)
        self.formLayout.addWidget(self.queryLabel, 1, 0)
        self.formLayout.addWidget(self.queryEdit, 1, 1)
        form.setLayout(self.formLayout)
        
        layout = QtGui.QVBoxLayout()
        layout.addWidget(form)
        layout.addWidget(self.btnBox)
        self.setLayout(layout)
        self.adjustSize()
        self.resize(self.width()+60, self.height())
        
    def showgroup(self, b):
        if b:
            self.groupBox.show()
            self.groupLabel.show()
        else:
            self.groupBox.hide()
            self.groupLabel.hide()
        self.formLayout.activate()
        self.setMaximumHeight(self.sizeHint().height())
        self.setMinimumHeight(self.sizeHint().height())
        self.resize(self.width(), self.minimumHeight())
                
    def _ok(self):
        self.ok = True
        self.close()
    
    def _getinput(self, title, group=None, txt=None, showGroup=True):
        self.setWindowTitle(title)
        if group is not None:
            i = self.groupBox.findText(group)
            if i != -1:
                self.groupBox.setCurrentIndex(i)
        if txt is not None:
            self.queryEdit.setText(txt)
        self.showgroup(showGroup)
        self.queryEdit.setFocus(QtCore.Qt.OtherFocusReason)
        self.ok = False
        self.show()
        self.exec_()
        return (self.ok,
               str(self.groupBox.currentText()),
               str(self.queryEdit.text()))
    
    def query(self, title, group=None, txt=None):
        return self._getinput(title, group, txt)
    
    def refine(self, title, txt=None):
        ok, group, query = self._getinput(title, None, txt, False)
        return ok, query
    
def main():
    app = QtGui.QApplication(sys.argv)
    
    w = QtGui.QWidget()
    w.resize(500, 200)
    w.show()
    
    d = InputDialog(w)
    print d.query("Query")
    
    print "hey"
    
    print d.refine("Refine")
    sys.exit()
    
    sys.exit(app.exec_())
    

if __name__ == "__main__": 
    main()